package com.zoweunion.mechanic.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.plugins.websocket.WebSocketServer;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.ToolCarDataService;
import com.zoweunion.mechanic.service.shangji.ShangJiService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import com.zoweunion.mechanic.util.task.*;
import com.zoweunion.mechanic.util.upload.UploadFile;
import com.zoweunion.mechanic.util.upload.UploadResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.origin.Origin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
public class TestController extends BaseController {

	@Autowired
	private AppService appService;
	@Autowired
	private AddressGEOUtil addressGEOUtil;
	@Autowired
	private ToolCarDataMapper toolCarDataMapper;
	@Autowired
	private DeviceStatisticsStoreTask deviceStatisticsStoreTask;
	@Autowired
	private CarFaultCodeTask carFaultCodeTask;
	@Autowired
	private ToolCarDataService toolCarDataService;
	@Autowired
	private ShangJiService shangJiService;
	@Autowired
	private JiGuangPushUtil jiGuangPushUtil;
//	@Autowired
//	private CarPositioningAccuracyTask carPositioningAccuracy;
	@Resource(name = "cachedThreadPool")
	private ExecutorService executorService;
	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RedisUtil redisUtil;

	public static final String redisktbl = "CATOnlineThings_";

	@PostMapping(value="/execut")
	public String execut() {
		logBefore(logger, "硬件测试开始");
//		List<Map<String,Object>> areaList=appService.getAreaAll();
			Map<String,Object> map=new HashMap<>();
			map.put("msg","我的水电费第三方");
			map.put("alias","3");
			System.out.println(jiGuangPushUtil.push(map));
		return "ok";
	}
	
	@PostMapping(value="/getStr",produces="text/plain")
	public String test(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "硬件测试开始");
		System.out.println(str);
		logAfter(logger);
		return "ok";
	}

	@PostMapping(value="/testAcceptData")
	public String testAcceptData(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "硬件测试开始");
		System.out.println(str);
		logAfter(logger);
		return "ok";
	}

	@PostMapping(value="/testWebSocketSendMessage")
	public ResponseBean testWebSocketSendMessage(@RequestBody String str, HttpServletRequest request) throws MyException {
		Map<String,String> result =new HashMap<>();
		result.put("code","10000");
		result.put("type","3");
		result.put("data","eny");
//		List<Map<String,Object>> list= null;
//		list.add(result);
		try {
//			JSON.toJSONString(result)
			new WebSocketServer().sendtoUser(JSON.toJSONString(result),"7");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	@PostMapping(value="/testUpdateFile")
	public ResponseBean updateFile(MultipartFile[] files , HttpServletRequest request){
		UploadResult uploadResult=null;
		try {
			for(MultipartFile file:files){
				uploadResult = UploadFile.uploadVideo(file,"others",request);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		//返回json
		 return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",uploadResult);
	}

	@Autowired
	private PushTask pushTask;

	@PostMapping(value = "/test")
	public ResponseBean test() throws Exception {
//		deviceStatisticsStoreTask.task();
//		carFaultCodeTask.task();
//		toolCarDataService.saveDataStatistics();
//		Map<String, Object> bodyMap = JSON.parseObject(body);
//		shangJiService.copyBuyInfoFile(bodyMap);
//		pushTask.carFuelGaugeLowPushTask();
//		pushTask.carWorkHoursReachMaintenance();
//		pushTask.carFaultPushTask();
		//carPositioningAccuracy.positioningAccuracy();

//		ArrayList<String> redisArray = new ArrayList<>();
//
//		for (int i = 0; i < 3000; i++) {
//
//			redisArray.add("170"+i);
//
//			Map<String,Object> tempMap = new HashMap<>();
//
//			tempMap.put("province","江苏省");
//			tempMap.put("city","无锡市");
//
//			tempMap.put("district","新区");
//
//			tempMap.put("province_code","340000");
//			tempMap.put("city_code","350");
//
//			tempMap.put("district_code","5141");
//
//			tempMap.put("GPSlongitude","132.0541");
//			tempMap.put("GPSlatitude","30.21");
//			tempMap.put("status",1);
//			tempMap.put("fault_status",1);
//			tempMap.put("things_id","170"+i);
//			tempMap.put("lock_status",2);
//
//			redisTemplate.opsForValue().set("170"+i,tempMap);
//		}

		//redisTemplate.opsForList().rightPushAll("redis_ceshi",redisArray);

		List<String> redisStr = redisUtil.getListString("redis_ceshi");

		ArrayList tempArray = new ArrayList();

		redisStr.forEach(item -> {

			tempArray.add(redisUtil.get(item));
		});

		/*
		ArrayList<Map<String, Object>> tempArray = toolCarDataMapper.getAllRealData();

		tempArray.forEach(item -> {

			try {

				String GPSlongitude = item.get("GPSlongitude").toString();
				String GPSlatitude = item.get("GPSlatitude").toString();
				String status = item.get("status").toString();
				String fault_status = item.get("fault_status").toString();
				String things_id = item.get("things_id").toString();
				if (GPSlatitude != null) {

					JSONObject region = addressGEOUtil.getRegion(GPSlongitude.toString(), GPSlatitude.toString());

					String city = region.getString("city");
					String province = region.getString("province");

					if (region.get("city").toString().equals("[]")) {

						city = province;
					}

					String provinceCode = toolCarDataMapper.getCode(province);
					String cityCode = toolCarDataMapper.getCode(city);

					Map<String,Object> tempMap = new HashMap<>();

					tempMap.put("province",province);
					tempMap.put("city",city);

					tempMap.put("district",region.getString("district"));

					tempMap.put("province_code",provinceCode);
					tempMap.put("city_code",cityCode);

					tempMap.put("district_code",region.getString("adcode"));

					tempMap.put("GPSlongitude",GPSlongitude);
					tempMap.put("GPSlatitude",GPSlatitude);
					tempMap.put("status",status);
					tempMap.put("fault_status",fault_status);
					tempMap.put("things_id",things_id);
					tempMap.put("lock_status",2);

					System.out.print(tempMap);

					//6bd970ddd3e44e0f8646f951453ce18e
					//a892450bd6084f4484a5479e0a9c1b23
					//district_code province_code city_code province city district
					//redisTemplate.opsForList().rightPushAll("6bd970ddd3e44e0f8646f951453ce18e_things_info",tempMap);
					toolCarDataMapper.updateReal(tempMap);
				}
			}catch (Exception e) {
				// TODO: handle exception
			}

		});
*/
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", tempArray);
	}



	@GetMapping(value="/insertTer")
	public ResponseBean insertTer(){
		List<String> list = toolCarDataMapper.selectTer();
		list.forEach(item->{
			int tid=0;
			int trid=0;
			Map<String, Object> terminalAdd = addressGEOUtil.terminalAdd("DIS"+item);
			Map parseObject = JSON.parseObject(terminalAdd.get("data").toString(), Map.class);
			tid=Integer.valueOf(parseObject.get("tid").toString());
			//创建轨迹
			Map<String, Object> traceAdd = addressGEOUtil.terminalTraceAdd(tid);
			Map parseObject1 = JSON.parseObject(traceAdd.get("data").toString(), Map.class);
			trid=Integer.valueOf(parseObject1.get("trid").toString());
			//插入轨迹
			toolCarDataMapper.insertTrid("DIS"+item,tid,trid, UuidUtil.get32UUID());
		});
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}


	@GetMapping(value="/insertLocation")
	public ResponseBean insertLocation(){
		List<Map<String,Object>> list = toolCarDataMapper.selectLocation();
		executorService.execute(() -> {
			list.parallelStream().forEach(item->{
				int thingsId = toolCarDataMapper.selectCountLocation(item.get("thingsId").toString());
				for (int i=0; i<thingsId;i++){
					//查询临时表经纬度
					List<GpsTemp> locationTemp = toolCarDataMapper.
							selectLocationTemp(item.get("thingsId").toString(),i);
					if (locationTemp.size()==0){
						break;
					}
					if (locationTemp.size()>0){
						try {
							addressGEOUtil.tracePointAdd(Integer.valueOf(item.get("tid").toString()),
									Integer.valueOf(item.get("trid").toString()),
									JSONArray.parseArray(JSON.toJSONString(locationTemp)));//插入轨迹id
							//删除临时表数据
							List<Long> longs = locationTemp.stream().map(GpsTemp::getId).collect(Collectors.toList());
							String ids = "'" + StringUtils.join(longs, "','") + "'";
							toolCarDataMapper.deleteGpsTemp(ids);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				}
			});
		});

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}


	@GetMapping(value="/insertCat")
	public void insertCat(@RequestParam Map<String,Object> params) throws MyException {
		int day = 0;
		String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now().minusDays(day));
		List<String> list =  redisUtil.getListString(redisktbl + date);
		list.forEach(item->{
			String device = toolCarDataMapper.selectDp(item);
			List<Map<String, Object>> selectfast =
					toolCarDataMapper.selectfast("pc_car_data_fast" + device, params, item);
			//查询键
			String table = Orgin.getString(params, "table");
			List<String> strings = toolCarDataMapper.selectPcCarColumnList(table);
			Map<String, Object> objects = new HashMap<>();
			if (selectfast.size()>0){
				for (Map<String, Object> item1 : selectfast) {
					for (Map.Entry<String, Object> entry : item1.entrySet()) {
						if (strings.contains(entry.getKey())){
							objects.put(entry.getKey(), entry.getValue());
						}
					}
					objects.put("data_id",UuidUtil.get32UUID());
					List<Map<String, Object>> maps = toolCarDataMapper.selectTableValue(table, objects);
					if (maps.size()==0){
						//插入分表数据
						toolCarDataMapper.insertTableValue(table,objects);
					}
				}
			}
		});
	}

	@GetMapping(value="/insertProject")
	public void insertProject(@RequestParam Map<String,Object> params) throws MyException {
		for (int i = 0; i < 10000; i +=1 ) {
			Integer pageSize = Orgin.getIntValue(params,"pageSize");
			Integer currentPage = Orgin.getIntValue(params,"currentPage");
			PageHelper.startPage(currentPage+i, pageSize);
			List<Map<String, Object>> maps = toolCarDataMapper.selectZoweProject();
			maps.parallelStream().forEach(item->{
				toolCarDataMapper.insertZowePro(item);
				}
			);
			System.out.println("------xxx"+i);
		}
	}



	public static void main(String[] args) {


	}
}
